package com.xuan.web;
import com.xuan.dao.UserDao;
import com.xuan.model.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/LoginAction")
@SuppressWarnings("all")
public class LoginAction extends HttpServlet {
    private UserDao userDao = new UserDao();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String verifyCode = (String) request.getSession().getAttribute("verifyCode");
        if(verifyCode==null || !verifyCode.equalsIgnoreCase(request.getParameter("verifyCode"))){
            Map<String,String> errors=new HashMap<>();
            errors.put("verifyCode","验证码错误.");
            forward(request,response,"errors",errors,"login.jsp");
            return;
        }
        String mob = request.getParameter("mob");
        String password = request.getParameter("password");
        User user = userDao.login(mob,password);
        if (user == null) {
            forward(request,response,"您输入的手机号或密码有误","login.jsp");
        }
        Cookie cookie = new Cookie("mob",mob);
        cookie.setPath("/");
        if("1".equals(request.getParameter("saveUserFlag"))){
            cookie.setMaxAge(7*24*86400);
        }else{
            cookie.setMaxAge(0);
        }
        response.addCookie(cookie);
        request.getSession().setAttribute("loginEmp",user);
//        forward(request,response,"","servlet/ServiceTypeAction?act=list");
        forward(request,response,"","index1.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("loginEmp");
        forward(request,response,"退出程序","login.jsp");
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String key, Object value, String url) throws ServletException, IOException {
        request.setAttribute(key, value);
        request.getRequestDispatcher(url).forward(request, response);
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String msg, String url) throws ServletException, IOException {
        request.setAttribute("msg", msg);
        request.getRequestDispatcher(url).forward(request, response);
    }
}
